#pragma once
#include <iostream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string>
#include <stdarg.h>
#include <string.h>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4

#define SIZE 1024
#define LOGFILE "log.txt"
#define Screen 1
#define Onefile 2
#define Classfiles 3

class log
{
public:
    log()
    {
        _printMethod = Screen;
        _path = "./log/";
    }

    void Enable(int method)
    {
        _printMethod = method;
    }

    string levelString(int level)
    {
        switch (level)
        {
        case Info:
            return "Info";
            break;
        case Debug:
            return "Debug";
            break;
        case Warning:
            return "Warning";
            break;
        case Error:
            return "Error";
            break;
        case Fatal:
            return "Fatal";
            break;
        default:
            return "None";
            break;
        }
    }

    void printLog(int level, const string& logTxt)
    {
        switch (_printMethod)
        {
        case Screen:
            cout << logTxt << endl;
            break;
        case Onefile:{
            string filePath = _path + string(LOGFILE);
            cout << filePath<<endl;
            printOneFile(filePath, logTxt);
            break;
        }
        case Classfiles:
            printClassfiles(level, logTxt);
            break;
        default:
            break;
        }
    }
    

    void printOneFile(const string &filePath, const string& logTxt){
        cout << filePath.c_str()<<endl;
        int fd = open(filePath.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
        if(fd < 0){
            perror("path");
            return;
        }
        write(fd, logTxt.c_str(), logTxt.size());
        close(fd);
    }

    void printClassfiles(int level, const string& logTxt){
        string filePath = _path + string(LOGFILE) + "." + levelString(level);
        printOneFile(filePath, logTxt);
    }

    void operator()(int level, const char *format, ...)
    {
        time_t stamp = time(nullptr);
        struct tm *t = localtime(&stamp);
        char defaultbuf[SIZE];
        snprintf(defaultbuf, sizeof(defaultbuf), "[%s][%d-%d-%d %d:%d:%d]", levelString(level).c_str(),
                 t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);

        char logbuf[SIZE];
        va_list s;
        va_start(s, format);
        vsnprintf(logbuf, sizeof(logbuf), format, s);
        va_end(s);

        string all = string(defaultbuf) + ' ' + logbuf + '\n';
        printLog(level, all);
    }

private:
    int _printMethod;
    string _path;
};
